**
** use results from T:\bb_lake_chad_rem\agr_prep_landcover_reclass_crosstab_1992_2019.r
** 36 points c(831,1476,1856,3191,3302,4005,4808,4846,6378,6880,7191,7436,7792,8071,9940,10290,10558,11139,12057,12527,12528,12643,12728,13337,14472,15118,15283,18375,19148,19604,20175,21076,21890,27404,28842,32478)

**
** reclass matrix
* 0 = no data
* 1 = cropland
* 2 = cropland mosaic
* 3 = grassland (130)
* 4 = urban
* 5 = bare 
* 6 = other
* 7 = water
* 8 = irrigation


// Get the path of the currently running do-file
local do_file_path `c(pwd)'

// Change the working directory to the location of the do-file
cd "`do_file_path'"

cd "local\gis_data\LULCfreq"

clear
append using `: dir . files "*.dta"'
destring objectid, replace
sort objectid year

* redefine grassland to other
label define lulc 3 "Other", modify
* add other categories
replace lulc=3 if inlist(lulc,5,6,7)

* add shares with reclass
collapse (sum) sh_lulc, by(objectid year lulc)

label variable lulc "Landcover (type) reclass : ESA"
label define lulclabel 0 "NA" 1 "cropland" 2 "cropland mosaic" 3 "other" 4 "urban" 8 "irrigated"
label values lulc lulclabel
rename sh_lulc sh_pixel
label variable sh_pixel "Share of pixels with lulc class in grid : ESA"

cd "`do_file_path'"
save "proc_data\LULCfreq_ts_9219.dta", replace

clear
use "proc_data\LULCfreq_ts_9219.dta"
reshape wide sh_pixel, i(objectid year) j(lulc)

rename sh_pixel1 sh_crop
rename sh_pixel2 sh_crpm
rename sh_pixel3 sh_othr
rename sh_pixel4 sh_urbn
rename sh_pixel8 sh_irrg

label variable sh_crop "Share of pixels with crop in grid : ESACCI-LC-L4 300m"
label variable sh_crpm "Share of pixels with crop mosaic in grid : ESACCI-LC-L4 300m"
label variable sh_othr "Share of pixels with other lulc in grid : ESACCI-LC-L4 300m"
label variable sh_urbn "Share of pixels with urban in grid : ESACCI-LC-L4 300m"
label variable sh_irrg "Share of pixels with irrigated in grid : ESACCI-LC-L4 300m"

*add area
merge m:1 objectid using "proc_data\GRIDAGR.dta" 

drop _merge

g crop = areakm2 * sh_crop
g crpm = areakm2 * sh_crpm
g othr = areakm2 * sh_othr
g urbn = areakm2 * sh_urbn
g irrg = areakm2 * sh_irrg

label variable crop "Crop area in grid (km2) : ESACCI-LC-L4 300m"
label variable crpm "Crop mosaic area in grid (km2) : ESACCI-LC-L4 300m"
label variable othr "Other lulc area in grid (km2) : ESACCI-LC-L4 300m"
label variable urbn "Urban area in grid (km2) : ESACCI-LC-L4 300m"
label variable irrg "Irrigated area in grid (km2) : ESACCI-LC-L4 300m"

save "proc_data\LULCfreq_wide_ts_9219.dta", replace

save "proc_data\LULCfreq_ts_v2.dta", replace
